package org.yun.util;

import org.yun.biz.model.DrawRecord;
import org.yun.biz.model.RedPack;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import static org.yun.biz.model.DrawRecord.initRecord;

/**
 * @author liyunfeng31
 */
public class RandomRedUtil {

    /**
     * 线程安全的random
     */
    public static final Random random = ThreadLocalRandom.current();


    /**
     * 分配红包
     * @param redPack redPack
     * @return list
     */
    public static List<DrawRecord> allocateRedPack(RedPack redPack){
        Integer num = redPack.getNum();
        Integer amount = redPack.getAmount();
        Long redPackId = redPack.getRedPackId();
        List<DrawRecord> pak = new ArrayList<>();
        while(num > 1){
            Integer m = randomRed(num,amount);
            num -- ;
            amount -= m;
            pak.add(initRecord(redPackId,m));
        }
        pak.add(initRecord(redPackId,amount));
        return pak;
    }


    /**
     * 随机数
     * @param rNum 剩余个数
     * @param rAmount 剩余金额
     * @return 金额(分)
     */
    public static Integer randomRed(Integer rNum , Integer rAmount){
        return random.nextInt(rAmount / rNum * 2 - 1) + 1;
    }

}
